package com.jch.mp.manner1.client;

import com.jch.mp.manner1.codec.MsgDecoder;
import com.jch.mp.manner1.codec.MsgEncoder;
import com.jch.mp.manner1.domain.message.ComplexMessage;
import com.jch.mp.manner1.domain.message.GroupMessage;
import com.jch.mp.manner1.domain.message.SimpleMessage;
import com.jch.mp.manner1.domain.message.other.TestData;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Manner1Client {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss:SSS");

    public static void main(String[] args) {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.AUTO_READ, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MsgDecoder());
                        ch.pipeline().addLast(new MsgEncoder());

                        ch.pipeline().addLast(new Manner1ClientHandler());
                    }
                });
        try {
//            ChannelFuture channelFuture = b.connect("127.0.0.1", 1132).sync();
            ChannelFuture channelFuture = b.connect("127.0.0.1", 1135).sync(); // 测试Manner2

            System.out.println(dateFormat.format(new Date()) + " Manner1 Client Start done.");

            channelFuture.channel().writeAndFlush(new SimpleMessage("简单信息。"));
            channelFuture.channel().writeAndFlush(new GroupMessage(1,"测试","狂徒张三"));
            channelFuture.channel().writeAndFlush(new ComplexMessage(1,new TestData(12,"TestData类 | 123四五六柒捌玖",new Date())));

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

}
